<template>
  <div class="addPatient">
    <div class="addPatient-content">
      
      <div class="dynamic f-w" v-if="isRefreshPage">
          <ztitleBorder title="患者信息">
              <component :is="showWidget(item.type)"  v-for="item in infoAdd" :key="item.name" :struc="item"  />
          </ztitleBorder>
      </div>
      <div class="dynamic f-w">
          <ztitleBorder title="客户关系">
              <component :is="showWidget(item.type)"  v-for="item in resultAdd" :key="item.name" :struc="item"  />
          </ztitleBorder>
      </div>
      <div class="dynamic f-w">
          <ztitleBorder title="客户初诊">
              <component :is="showWidget(item.type)"  v-for="item in DiagnosisAdd" :key="item.name" :struc="item"  />
          </ztitleBorder>
      </div>
    </div>
    <div class="addPatient-footer">
      <el-button class="btn-2" @click="cancel">取消</el-button>
      <el-button class="btn-2" @click="saveAndRegister">保存并挂号</el-button>
      <el-button class="btn-2" @click="saveMakeAnAppointment">保存并预约</el-button>
      <el-button class="btn-1" @click="save">保存患者</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, isVNode, onUnmounted, ref, watchEffect, nextTick } from '@vue/runtime-core';
import ztitleBorder from "../titleBorder/titleBorder.vue"

import useShowWidget from "../widget/usechoose";
import useRequet, { RespData } from "../../hook/network"
import useConfgin from '../../hook/getconfig'

import useDataCheck from '../../hook/datastruc'
import { getCreateHistoryNum } from '../../usefn/getDoctor'

import { ElMessage } from 'element-plus'
import { getNowDates } from '../../utils/nowDate';
import { Message } from '@element-plus/icons-vue/dist/types';
import { useRouter } from 'vue-router';
import router from '../../router';

const ID = 518 // 患者中心
const RELATION = 519 // 患者关系
const INITIALDIAGNOSIS = 520 // 客户初诊
export default defineComponent({
  components: {
    ztitleBorder
  },
  setup(props, ctx) {
    const router = useRouter()
    const dataCheck = useDataCheck();
    const request = useRequet({ path: "" });

    const isRefreshPage = ref(true)

    const infoTotal = useConfgin(ID)
		let infoAdd = infoTotal.groupDataAdd
    
    const resultTotal = useConfgin(RELATION)
		const resultAdd = resultTotal.groupDataAdd
		const InitialDiagnosis = useConfgin(INITIALDIAGNOSIS)
		const DiagnosisAdd = InitialDiagnosis.groupDataAdd;
    // 添加成功跳转
    const isToJump = ref()

    
    watchEffect(() => {
      infoAdd.value.forEach(async(i) => {
        if(i.name === 'historySickNum') {
          i.value = await getCreateHistoryNum()
        }
      })

      DiagnosisAdd.value.forEach(i => {
        if(i.name === 'startTime') {
          i.value = getNowDates() + ' ' + '00:00:00'
        }
      })
    })


    let userId = ref()

    const showWidget = useShowWidget;
    
    
    type Records = {
			startTime: string,
			primaryCareDoctor: number,
			actionChief: string,
			preliminaryJudgment: string,
			symptoms: string
		}
    const save = () => {
      console.log('保存')
			let result = {
				customerInfo:{
					other: {}
				},
				deptConfig: {},
				records: {} as Records
			} as any
			infoAdd.value.forEach(item => {
				// if(item.type === 502 && item.value) {
				// 	item.value = setTime(item.value)
				// }
				if(item.name.split('.')[0] === 'other') {
					result.customerInfo.other[item.name.split('.')[1]] = item.value
				} else {
					result.customerInfo[item.name]= item.value
				}
			})
			resultAdd.value.forEach(item => {
				// console.log('resultAdd', item)
				// if(item.type === 502 && item.value) {
				// 	item.value = setTime(item.value)
				// }
				result.deptConfig[item.name] = item.value
			})
			DiagnosisAdd.value.forEach(item => {
        // if(item.type === 502 && item.value) {
				// 	item.value = item.value + ' ' + '00:00:00'
				// }
				result.records[item.name] = item.value
			})
      
      console.log(result)
      if(result.customerInfo)
      for(let i in result.customerInfo) {
        console.log(i)
        if(i == 'certificateType' && !result.customerInfo['certificateType']) {
          result.customerInfo[i] = null
        }
        if(i == 'gender' && !result.customerInfo['gender']) {
          ElMessage.warning('还未选择性别哦')
          return
        }
        if(i == 'name' && !result.customerInfo['name']) {
          ElMessage.warning('还未填写姓名哦')
          return
        }
        if(i == 'birthDate' && !result.customerInfo['birthDate']) {
          ElMessage.warning('还未填写生日哦')
          return
        }
        if(i == 'mobileNum' && !result.customerInfo['mobileNum'][0]['phone']) {
          ElMessage.warning('还未输入手机号哦')
          return
        }
      }
      console.log(result)
      
      // if(!dataCheck.checkAll()) {
      //     ElMessage.warning('还有未填信息哦')
      //     return false
      // }
      return new Promise((resolve, reject) => {
        request.sendRequest({
          address: 'customer/info/createCustomer',
          params: result,
          success: (resp: RespData) => {
            if(resp.code !== 0) {
              ElMessage.error('保存患者' + resp.msg)
              return false
            }
            ElMessage.success('保存患者' + resp.msg)
            if(isToJump.value === 'register') {

              userId.value = resp.data.id;
              ctx.emit('saveAndRegister', resp.data.id)
            }
            if(isToJump.value === 'appointment') {
              ctx.emit('saveMakeAnAppointment', resp.data.name, resp.data.id)
            }
            
            if(!isToJump.value) {
              cancel()
            }
            
            resolve('')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('保存患者' + resp.msg)
            reject()
          },
          method: "POST",
        })
      })
			
		}

    const cancel = async() => {
      isRefreshPage.value = false;
      console.log(infoAdd.value)
      infoAdd.value.forEach(async(i) => {
        i.value = ''
        if(i.name === 'historySickNum') {
          i.value = await getCreateHistoryNum()
        }

        if(i.name === 'mobileNum') {
          i.value = [
            {
              isAdd: true,
              phone: '',
              phoneToCustomerType: 1,
            }
          ]
        }

        if(i.name === 'phone') {
          i.value = [
            {
              isAdd: true,
              phone: '',
              phoneToCustomerType: undefined,
            }
          ]
        }

      })

      ctx.emit('cancel')
		}
    const saveAndRegister = () => {
      console.log('点击了保存并挂号')
      isToJump.value = 'register'
      save();
      
      
    }
    const saveMakeAnAppointment = () => {
      isToJump.value = 'appointment'
      save()
    }

    onUnmounted(() => {
			dataCheck.clearDataCheck();
		});
    return {
      infoAdd,
      resultAdd,
      DiagnosisAdd,

      isRefreshPage,

      cancel,
      saveMakeAnAppointment,
      saveAndRegister,
      save,

      showWidget,

      request
    }
  }

})
</script>

<style lang="scss" scoped>
.addPatient {
  display: flex;
  flex-direction: column;
  padding-top: 0;
  height: 100%;
  .addPatient-content {
    padding: 20px;
    height: calc(100% - 60px);
    overflow: auto;
  }
  .addPatient-footer {
    width: 100%;
    height: 60px;
    line-height: 60px;
    box-shadow: 0 0 3px rgba(0, 0, 0, .3);
    flex: 1;
    text-align: right;
    .btn-1 {
      margin-right: 40px;
    }
  }
}
</style>